package com.example.springboot.common.exception;

import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;


// 全局异常处理
@Slf4j
@RestControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(value = ServiceException.class)
    public Result exceptionError(ServiceException e) throws Exception {
        log.error("业务异常!", e);
        String code = e.getCode();
        // 如果code不为空
        if(StrUtil.isNotBlank(code)) {
            return Result.error(code, e.getMessage());
        }
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public Result exceptionError(Exception e) throws Exception {
        log.error("系统错误!", e);

        return Result.error("系统错误!", e.getMessage());
    }



    @ExceptionHandler(value = NoResourceFoundException.class)
    public Result handleNoResourceFoundException(NoResourceFoundException e) {
        log.error("请求的资源未找到: {}", e.getMessage());
        // 根据需要返回特定的错误码和消息
        return Result.error("404", "请求的资源未找到");
    }
}
